
$(function(){
	
	//管理员管理
	table_add_data('#AdminList','../admin/adminList');
	//角色管理
	table_add_data('#RoleList','../role/roleList');
	//会员管理
	table_add_data('#DMemberList','../dMember/dMemberList');
	//打印管理
	table_add_data('#DAdmissionTicketList','../dAdmissionTicket/dAdmissionTicketList');
	//图片管理
	table_add_data('#DSingleImageList','../dSingleImage/dSingleImageList');
	//文章管理
	table_add_data('#DRichTextList','../dRichText/dRichTextList');
	//学校管理
	table_add_data('#DSchoolList','../dSchool/dSchoolList');	
	//首页轮播图
	table_add_data('#HomeImageList','/bdyz/admin/homeImage/homeImageList');
	//花型加工工艺管理
	table_add_data('#PatternPrintsList','../patternPrints/patternPrintsList');
	//秀场地区管理 任凯伟
	table_add_data('#AreaList','../show/areaList');
	//秀场管理 任凯伟
	table_add_data('#ShowListTable','../show/list');
	//面料属性管理 任凯伟
	table_add_data('#FabricFilterTable','../fabricFilter/list');
	//咨询管理
	table_add_data('#ConsultList','../consult/consultList');
	//轮播图管理
	table_add_data('#imgList','../consult/imgList');
	//用户管理
	table_add_data('#Member','../memberManage/memberManageList');
	//花型属性管理
	table_add_data('#PatternFilter','../patternfilter/list');
	//花型预设标签管理
	table_add_data('#PatternFilter1','../patternfilter/list2');
	//花型预设标签（大类列表）
	table_add_data('#PatternFilterBig','../patternfilter/listBig');
	//花型属性管理
	table_add_data('#OrdersList','../../admin/orders/listorders');
	//花型主题管理
	table_add_data('#ThemeList','../../admin/theme/themeList');
	//测试
	table_add_data('#AaList','../../admin/aa/aaList');
	//会员省区统计
	table_add_data('#memberProvinceList','../../admin/memberManage/memberProvinceList');
	//会员访问排名（日）
	table_add_data('#memberSortDayList','../../admin/memberSort/memberSortDayList');
	//会员访问排名（周）
	table_add_data('#memberSortWeekList','../../admin/memberSort/memberSortWeekList');
	//会员访问排名（月）
	table_add_data('#memberSortMonthList','../../admin/memberSort/memberSortMonthList');
	//会员访问排名（所有）
	table_add_data('#memberSortAllList','../../admin/memberSort/memberSortAllList');
	
	//面料管理 任凯伟
	table_add_data('#FabricTable','../fabric/list');
	//花型列表
	table_add_data('#Patterns','../Patterns/PatternList');	
	
	
	
	
	
});

function table_add_data(tableId,tableDataUrl){
	var tableLength=$(tableId).length;
	//判断是否是当前页，如果是则执行，否则就不执行，这样在页面很多时可以大幅加快列表的显示速度。
	if(tableLength>0){
	//判断是否启用排序功能
	var data_sortable_length=$(tableId).find('thead').find('th[data-sortable]').length;
	if(data_sortable_length>0){
		var sort=true;
	}else{
		var sort=false;
	}
	
	var columnsArray=[];
	//table表头添加checkbox复选框
	var ths=$(tableId).find('thead').find('th[data-field]');
	var keyObj={};
	keyObj.data=null;
	keyObj.sClass='text-c';
	keyObj.mRender=function(data, type, full){
		var columnHtml='';
		var ID_Val=ths.eq(0).attr('data-field');
		if(ID_Val in data){
			columnHtml='<input type="checkbox" value="'+data[ID_Val]+'" name="">';
		}
	    return columnHtml;
	}
	// {"orderable":false,"aTargets":[0]}// 制定列不参与排序
	keyObj.orderable=false;    //是否可以排序，默认不可以
	keyObj.aTargets=[0];       //参与字段，默认是第一个字段（）
	columnsArray.push(keyObj);
	ths.each(function(){
		//alert($(this).index());
			var keyString=$(this).attr('data-field');
			var formatterString=$(this).attr('data-formatter');
			var data_sortable=$(this).attr('data-sortable');
			var keyObj={};
			keyObj.data=keyString;
			keyObj.sClass='text-c';
			if(formatterString=='dateFormatter'){
				//时间日期格式化
				keyObj.mRender=function(data, type, full){
					if(full[keyString]==null||full[keyString]==""||full[keyString]=="null"){
						return '暂无';
					}else{
						return moment(full[keyString]).format('YYYY-MM-DD HH:mm:ss');
					}
				}
			}else if(formatterString=='imgFormatter'){
				//图片格式化
				keyObj.mRender=function(data, type, full){
					if(full[keyString]==null||full[keyString]==""||full[keyString]=="null"){
						return '暂无';
					}else{
						return '<img style="width: 80px;height: 120px;" alt="" src="../../upload/'+full[keyString]+'">';
					}
				}
			}else if(formatterString!=undefined&&formatterString!='undefined'&&formatterString!=''){
				keyObj.mRender=function(data, type, full){
					var aafunction=eval(formatterString);
					return aafunction(full[keyString]);
				}
			}
			//如果排序字段存在
			if(data_sortable!=null&&data_sortable!=undefined&&data_sortable!=''){
				//1、表示升序；2、表示降序；3、表示升序和降序同时存在;4、表示禁用排序
				if(data_sortable==1){
					keyObj.orderSequence=[ "asc" ];
				}else if(data_sortable==2){
					keyObj.orderSequence=[ "desc" ];
				}else if(data_sortable==3){
					keyObj.orderSequence=[ "desc", "asc" ];
				}else if(data_sortable==4){
					keyObj.orderSequence=[ null ];
				}
			}
		columnsArray.push(keyObj);
	});
	var tables =$(tableId).dataTable({
		"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
		"destroy": true,//如果需要重新加载的时候请加上这个
    	"bProcessing" : true,//加载数据时候是否显示进度条
    	"bServerSide" : true,//是否从服务加载数据 ,
    	 "bInfo": true,   //如果这个参数不穿到后台去，服务器分页会报错，据说这个参数包含了表的所有信息 
         "bPaginate": true,   //是否显示（应用）分页器  
         "bStateSave":true,//保存状态
         "bSort" : sort, //是否启动各个字段的排序功能 
         /*"aoColumns": [        //排序方式
                       null,
                       null,
                       { "orderSequence": [ "asc" ] },
                       { "orderSequence": [ "desc", "asc", "asc" ] },
                       { "orderSequence": [ "desc" ] },
                   ]*/
         "aaSorting": [[ 2, "desc" ]],//默认第几个排序(在启用排序的情况下会自动排序，否则就不会)
         "searching": false,      //搜索不显示
         "bScrollCollapse" : true, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变  
    	"sAjaxSource" : tableDataUrl,//如果从服务器端加载数据,这个属性用于指定加载的路径 
    	"sServerMethod": "POST",   //以post的方式提交数据
    	"fnServerParams": function ( aoData ) {         //向服务器传递额外的参数
    		var inputs=$('#search').find('input,select');
    		inputs.each(function(){
    			var idString=$(this).attr('id');
    			aoData.push( { "name": idString, "value": $(this).val() } );
    		});
   	    },
    	"columns":columnsArray,
        "fnRowCallback" : function(nRow, aData, iDisplayIndex) { 
        	//nRow   代表的是每一行
        	//aData    代表的是服务器端返回的数据
               /* td表格元素内部的文本替换 */
        	/*var dataFields=$(tableId).find('th[data-field]');
        	dataFields.each(function(){
        		var keyString=$(this).attr('data-field');
        		var formatterString=$(this).attr('data-formatter');
        		if(formatterString=='AA'){
        			var aaaaaaa=eval(formatterString);
        			aaaaaaa();
        		}
        	});*/
               return nRow;  
           }, 
    	/*"sPaginationType" : "full_numbers",*/
    	"sPaginationType" : "bootstrap",
    	"oLanguage" : { //主要用于设置各种提示文本
	    	"sProcessing" : "正在处理...", //设置进度条显示文本
	    	"sLengthMenu" : "每页_MENU_行",//显示每页多少条记录
	    	"sEmptyTable" : "没有找到记录",//没有记录时显示的文本
	    	"sZeroRecords" : "没有找到记录",//没有记录时显示的文本
	    	"sInfo" : "总记录数_TOTAL_当前显示_START_至_END_",
	    	"sInfoEmpty" : "",//没记录时,关于记录数的显示文本
	    	"sSearch" : "搜索:",//搜索框前的文本设置
	    	"oPaginate" : {
	    	"sFirst" : "首页",
	    	"sLast" : "末页",
	    	"sNext" : "下页",
	    	"sPrevious" : "上页"
	    	}
    	}//用于设置提示文本 
	});
	}else{
		
	}
}

//前端分页方法
/*$('.table-sort').dataTable({
	"aaSorting": [[ 1, "desc" ]],//默认第几个排序
	"bStateSave": true,//状态保存
	"aoColumnDefs": [
	  //{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
	  {"orderable":false,"aTargets":[0,8,9]}// 制定列不参与排序
	]
});*/

$.extend( true, $.fn.dataTable.defaults, {
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sSearch": "快速搜索:",
        "bAutoWidth": true,
        "sLengthMenu": "每页显示 _MENU_ 条记录",
        "sZeroRecords": "Nothing found - 没有记录",
        "sInfo": "_START_ 到 _END_ 条,共 _TOTAL_ 条",
        "sInfoEmpty": "显示0条记录",
        "sInfoFiltered": "(从 _MAX_ 条中过滤)",
        "sProcessing":"<div style=''><img src='../static/img/loader.gif'><span>加载中...</span></div>",
        "oPaginate": {
        	"sFirst" : "首页",
	    	"sLast" : "末页",
	    	"sNext" : "下页",
	    	"sPrevious" : "上页"
        }
    }
} );


/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline"
} );


/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
    return {
        "iStart":         oSettings._iDisplayStart,
        "iEnd":           oSettings.fnDisplayEnd(),
        "iLength":        oSettings._iDisplayLength,
        "iTotal":         oSettings.fnRecordsTotal(),
        "iFilteredTotal": oSettings.fnRecordsDisplay(),
        "iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
        "iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
    };
};

	


/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
    "bootstrap": {
        "fnInit": function( oSettings, nPaging, fnDraw ) {
            var oLang = oSettings.oLanguage.oPaginate;
            var fnClickHandler = function ( e ) {
                e.preventDefault();
                if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                    fnDraw( oSettings );
                }
            };

            $(nPaging).addClass('pagination').append(
                '<ul>'+
                '<li class="first disabled"><a href="#">'+oLang.sFirst+'</a></li>'+
                '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+
                '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+
                '<li class="last disabled"><a href="#">'+oLang.sLast+'</a></li>'+
                '<input type="text" style="width: 30px;padding-top: 5px;padding-bottom: 5px;height: 18px;border-left: 0px;border-radius: 0px 4px 4px 0px;" id="redirect" class="redirect">'+
                '</ul>'
                );

            //datatables分页跳转
            $(nPaging).find(".redirect").keyup(function(e){
                var ipage = parseInt($(this).val());
                var oPaging = oSettings.oInstance.fnPagingInfo();
        		if(isNaN(ipage) || ipage<1){
                    ipage = 1;
                }else if(ipage>oPaging.iTotalPages){
                    ipage=oPaging.iTotalPages;
                }
                $(this).val(ipage);
                ipage--;
                oSettings._iDisplayStart = ipage * oPaging.iLength;
                fnDraw( oSettings );
        	});

            var els = $('a', nPaging);
            $(els[0]).bind( 'click.DT', {
                action: "first"
            }, fnClickHandler );
            $(els[1]).bind( 'click.DT', {
                action: "previous"
            }, fnClickHandler );
            $(els[2]).bind( 'click.DT', {
                action: "next"
            }, fnClickHandler );
            $(els[3]).bind( 'click.DT', {
                action: "last"
            }, fnClickHandler );
        },

        "fnUpdate": function ( oSettings, fnDraw ) {
            var iListLength = 5;
            var oPaging = oSettings.oInstance.fnPagingInfo();
            var an = oSettings.aanFeatures.p;
            var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

            if ( oPaging.iTotalPages < iListLength) {
                iStart = 1;
                iEnd = oPaging.iTotalPages;
            }
            else if ( oPaging.iPage <= iHalf ) {
                iStart = 1;
                iEnd = iListLength;
            } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                iStart = oPaging.iTotalPages - iListLength + 1;
                iEnd = oPaging.iTotalPages;
            } else {
                iStart = oPaging.iPage - iHalf + 1;
                iEnd = iStart + iListLength - 1;
            }

            for ( i=0, ien=an.length ; i<ien ; i++ ) {
                // Remove the middle elements
                ($('li:gt(1)', an[i]).filter(':not(:last)')).filter(':not(:last)').remove();

                // Add the new list items and their event handlers
                for ( j=iStart ; j<=iEnd ; j++ ) {
                    sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                    $('<li '+sClass+'><a href="#">'+j+'</a></li>')
                    .insertBefore( $('.next', an[i])[0] )
                    .bind('click', function (e) {
                        e.preventDefault();
                        oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                        fnDraw( oSettings );
                    } );
                }

                // Add / remove disabled classes from the static elements
                if ( oPaging.iPage === 0 ) {
                    $('li:lt(2)', an[i]).addClass('disabled');
                } else {
                    $('li:lt(2)', an[i]).removeClass('disabled');
                }

                if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                    $('.next', an[i]).addClass('disabled');
                    $('li:last', an[i]).addClass('disabled');
                } else {
                    $('.next', an[i]).removeClass('disabled');
                    $('li:last', an[i]).removeClass('disabled');
                }
            }
        }
    }
} );


/*
 * TableTools Bootstrap compatibility
 * Required TableTools 2.1+
 */
if ( $.fn.DataTable.TableTools ) {
    // Set the classes that TableTools uses to something suitable for Bootstrap
    $.extend( true, $.fn.DataTable.TableTools.classes, {
        "container": "DTTT btn-group",
        "buttons": {
            "normal": "btn",
            "disabled": "disabled"
        },
        "collection": {
            "container": "DTTT_dropdown dropdown-menu",
            "buttons": {
                "normal": "",
                "disabled": "disabled"
            }
        },
        "print": {
            "info": "DTTT_print_info modal"
        },
        "select": {
            "row": "active"
        }
    } );

    // Have the collection use a bootstrap compatible dropdown
    $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
        "collection": {
            "container": "ul",
            "button": "li",
            "liner": "a"
        }
    } );
}
